package com.dzl.moive.service.impl;

import com.dzl.constant.CommonConstants;
import com.dzl.micro.pojo.WelfareMicroPage;
import com.dzl.micro.service.WelfareMicroPageService;
import com.dzl.moive.dao.WelfareMovieInfoMapper;
import com.dzl.moive.pojo.WelfareMovieInfo;
import com.dzl.moive.pojo.WelfareMoviePremiumPriceCache;
import com.dzl.moive.pojo.dto.WelfareMoviePremiumPriceDto;
import com.dzl.moive.pojo.query.WelfareMovieCinemaQuery;
import com.dzl.moive.pojo.query.WelfareMovieCityQuery;
import com.dzl.moive.pojo.query.WelfareMovieInfoManageQuery;
import com.dzl.moive.pojo.vo.*;
import com.dzl.moive.service.WelfareMovieCinemaService;
import com.dzl.moive.service.WelfareMovieInfoService;
import com.dzl.moive.service.WelfareMoviePremiumPriceCacheService;
import com.dzl.moive.utils.MovieConstant;
import com.dzl.moive.utils.MovieUtils;
import com.dzl.util.DateUtil;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 电影基础信息(welfare_movie_info)表服务实现类
 * @author liuguanjun
 * @since 2021-11-02 11:14:42
 */
@Service("welfareMovieInfoService")
public class WelfareMovieInfoServiceImpl implements WelfareMovieInfoService {

    @Autowired
    private WelfareMovieInfoMapper mapper;
    @Autowired
    private WelfareMoviePremiumPriceCacheService welfareMoviePremiumPriceCacheService;
    @Autowired
    private WelfareMovieCinemaService welfareMovieCinemaService;
    @Autowired
    private WelfareMicroPageService welfareMicroPageService;

    @Override
    public List<WelfareMovieInfo> getMovieInfoList(String citycode, Integer type) {
        List<WelfareMovieInfo> list = new ArrayList<>();
        if (type == MovieConstant.MOVIE_TYPE.HOT) {
            list = MovieUtils.getMovieHotList(citycode);
        } else if (type == MovieConstant.MOVIE_TYPE.FATURE) {
            list = MovieUtils.getMovieFutureList(citycode);
        }
        return list;
    }

    @Override
    public WelfareMovieInfoVo getMovieInfoDetail(WelfareMovieCinemaQuery query) {
        WelfareMovieInfoVo welfareMovieInfoVo = new WelfareMovieInfoVo();
        WelfareMovieInfo welfareMovieInfo = getMovieInfo(query.getMovieid());
        if (EmptyUtils.isNotEmpty(welfareMovieInfo)) {
            BeanUtils.copyProperties(welfareMovieInfo,welfareMovieInfoVo);
        }
        //获取开始时间
        String startDay = DateUtil.getToday();
        if(EmptyUtils.isEmpty(query.getPlaydate())){
            query.setPlaydate(DateUtil.getToday());
        }
        if(welfareMovieInfo.getCanbuy().equals("true") && EmptyUtils.isNotEmpty(welfareMovieInfo.getBuytype()) && welfareMovieInfo.getBuytype().equals("prebuy")){//预售,则根据预售日期查
            startDay = welfareMovieInfo.getPlaydate();
            if(query.getPlaydate().equals(DateUtil.getToday())){
                query.setPlaydate(welfareMovieInfo.getPlaydate());
            }
        }
        String cinemaids = MovieUtils.getMoviePlayCinemaList(query.getMovieid(),query.getCitycode(),query.getPlaydate());
        if(EmptyUtils.isNotEmpty(cinemaids)){
            query.setCinemaids(cinemaids);
            List<WelfareMovieCinemaVo> list = welfareMovieCinemaService.getWelfareMoviePlayCinemaVoList(query);
            if(EmptyUtils.isNotEmpty(list)){
                WelfareMovieCityQuery welfareMovieCityQuery = new WelfareMovieCityQuery();
                welfareMovieCityQuery.setParentcode(query.getCitycode());
                welfareMovieCityQuery.setCinemaids(cinemaids);
                //根据城市查全部地区影院分布
                List<WelfareMovieCountyVo> countyList = mapper.selectMovieCountyList(welfareMovieCityQuery);
                welfareMovieInfoVo.setCountyList(countyList);
                //查询最近场次
                /*list.forEach(x->{
                    List<WelfareMovieOpiDetailVo> opiVoList = MovieUtils.getMovieOpiList(x.getId());
                    StringBuffer opiStr = new StringBuffer();//最近场次
                    if(EmptyUtils.isNotEmpty(opiVoList)) {
                        int count = 0;
                        for (int i = 0; i < opiVoList.size(); i++) {
                            if (count <= 2) {
                                if (opiVoList.get(i).getMovieid().equals(query.getMovieid().toString())) {
                                    String playTime = opiVoList.get(i).getPlaytime().split(" ")[1];
                                    playTime = playTime.substring(0,playTime.length()-3);
                                    opiStr.append(playTime).append("|");
                                    count ++;
                                }
                            } else {
                                break;
                            }
                        }
                        if(EmptyUtils.isNotEmpty(opiStr) && opiStr.length()>1){
                            x.setRecentSessions(opiStr.substring(0,opiStr.length()-1));
                        }
                    }
                });*/
            }
            welfareMovieInfoVo.setCinemaList(list);
        }
        //获取日期
        List<WelfareMovieDateVo> dateList = getMovieDateList(query.getPlaydate(), startDay);
        welfareMovieInfoVo.setDateList(dateList);
        return welfareMovieInfoVo;
    }

    @Override
    public Map getMoviePageBannerList(Integer enterpriseId) {
        Map map = Maps.newHashMapWithExpectedSize(2);
        List<WelfareMoviePageBannerVo> list = mapper.selectMoviePageBannerList(enterpriseId);
        if(EmptyUtils.isNotEmpty(list)){
            for (WelfareMoviePageBannerVo banner:list) {
                banner.setImg(ImageUtils.setImageSrc(banner.getImg()));
            }
        }
        WelfareMicroPage query = new WelfareMicroPage();
        query.setIsMovie(CommonConstants.YES);
        query.setStatus(CommonConstants.YES);
        query.setEnterpriseId(enterpriseId);
        WelfareMicroPage welfareMicroPage = welfareMicroPageService.selectOne(query);
        if(EmptyUtils.isNotEmpty(welfareMicroPage)){
            map.put("pageTitle", welfareMicroPage.getName());
        }else{
            map.put("pageTitle", "电影专区");
        }
        map.put("bannerList", list);
        return map;
    }

    /*******
     * 获取今天及后面7天的日期
     * @return
     */
    public List<WelfareMovieDateVo> getMovieDateList(String curryDay,String startDay) {
        List<WelfareMovieDateVo> list = new ArrayList<>();
        long quot = DateUtil.getQuot(DateUtil.getToday(),startDay);
        for(int i=0;i<8;i++){
            WelfareMovieDateVo welfareMovieDateVo = new WelfareMovieDateVo();
            Date date  = DateUtil.getOffsetDate(i+ Integer.valueOf(quot+""));
            String fullDayName = DateUtil.format2Date(date);
            welfareMovieDateVo.setDayFullName(fullDayName);
            welfareMovieDateVo.setDayName(fullDayName.split("-")[1]+"-"+fullDayName.split("-")[2]);
            long quot_ = DateUtil.getQuot(DateUtil.getToday(),fullDayName);
            if(quot_==0){
                welfareMovieDateVo.setDay("今天");
            }else if(quot_==1){
                welfareMovieDateVo.setDay("明天");
            }else{
                welfareMovieDateVo.setDay(DateUtil.getWeekOfDate(date));
            }
            if(fullDayName.equals(curryDay)){
                welfareMovieDateVo.setIsChecked(CommonConstants.YES);
            }
            list.add(welfareMovieDateVo);
        }
        return list;
    }

    @Override
    public WelfareMovieInfo getMovieInfo(Integer id) {
        WelfareMovieInfo movieInfo = mapper.selectByPrimaryKey(id);
        if (EmptyUtils.isEmpty(movieInfo)) {
            movieInfo = MovieUtils.getMovieDetail(id, null);
            movieInfo.setSaleCount(0);
            movieInfo.setCreateTime(new Date());
            movieInfo.setUpdateTime(new Date());
            //查询系统设置溢价
            WelfareMoviePremiumPriceCache welfareMoviePremiumPriceCache =  welfareMoviePremiumPriceCacheService.selectByPrimaryKey(1);
            if(EmptyUtils.isNotEmpty(welfareMoviePremiumPriceCache)){
                movieInfo.setPremiumPrice(welfareMoviePremiumPriceCache.getPremiumPrice());
            }else{
                movieInfo.setPremiumPrice(WelfareMovieInfo.premiumPriceDefault);
            }
            mapper.insertSelective(movieInfo);
        }else{
            //如果是预售电影，则重新调用api查询电影详情更新是否可购买的状态
            if(EmptyUtils.isNotEmpty(movieInfo.getBuytype()) && movieInfo.getBuytype().equals("prebuy")){
                WelfareMovieInfo movieInfo_ = MovieUtils.getMovieDetail(id, null);
                if(EmptyUtils.isNotEmpty(movieInfo_) && !movieInfo_.getBuytype().equals("prebuy")){
                    movieInfo.setUpdateTime(new Date());
                    movieInfo.setBuytype(movieInfo_.getBuytype());
                    movieInfo.setCanbuy(movieInfo_.getCanbuy());
                    movieInfo.setPlaydate(movieInfo_.getPlaydate());
                    mapper.updateByPrimaryKeySelective(movieInfo);
                }
            }
        }
        return movieInfo;
    }

    @Override
    public PageInfo<WelfareMovieInfo> getMovieInfoManageListPage(WelfareMovieInfoManageQuery query) {
        PageHelper.startPage(query);
        List<WelfareMovieInfo> list = mapper.getMovieInfoManageList(query);
        PageInfo<WelfareMovieInfo> page = new PageInfo<WelfareMovieInfo>(list);
        return page;
    }

    @Override
    public Integer updateMoviePremiumPrice(WelfareMoviePremiumPriceDto welfareMoviePremiumPriceDto) {
        String[] movieIdArray = welfareMoviePremiumPriceDto.getIds().split(",");
        List<Integer> idList = new ArrayList<>();
        for (String idStr : movieIdArray) {
            idList.add(Integer.parseInt(idStr));
        }
        if (idList.size() > 0) {
            Example example = new Example(WelfareMovieInfo.class);
            example.createCriteria().andIn("id", idList);
            WelfareMovieInfo welfareMovieInfoOpt = new WelfareMovieInfo();
            welfareMovieInfoOpt.setPremiumPrice(welfareMoviePremiumPriceDto.getPremiumPrice());
            return mapper.updateByExampleSelective(welfareMovieInfoOpt, example);
        }
        return 0;
    }

    @Override
    public Integer updateAllMoviePremiumPrice(BigDecimal premiumPrice) {
        // 订单溢出价格缓存
        Example exam = new Example(WelfareMoviePremiumPriceCache.class);
        exam.createCriteria().andEqualTo("id",1);
        WelfareMoviePremiumPriceCache welfareMoviePremiumPriceCacheOpt = new WelfareMoviePremiumPriceCache();
        // welfareMoviePremiumPriceCacheOpt.setId(1);
        welfareMoviePremiumPriceCacheOpt.setPremiumPrice(premiumPrice);
        welfareMoviePremiumPriceCacheService.updateByExampleSelective(welfareMoviePremiumPriceCacheOpt,exam);
        Example example = new Example(WelfareMovieInfo.class);
        WelfareMovieInfo welfareMovieInfoOpt = new WelfareMovieInfo();
        welfareMovieInfoOpt.setPremiumPrice(premiumPrice);
        return mapper.updateByExampleSelective(welfareMovieInfoOpt, example);
    }

    @Override
    public Integer updateMovieSaleCount(Integer movieid, Integer saleCount){
        return mapper.updateMovieSaleCount(movieid, saleCount);
    }
}